package com.vineetmanohar.nitrogen;

import java.io.StringWriter;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

/**
 * The code generation engine. Runs on an input in the context of a model.
 * 
 * @author vineetmanohar
 */
public class TextGenerator {
	public static String generateCode(
			CodeGenerationContext codeGenerationContext, String input) {

		ObjectModel model = codeGenerationContext.getObjectModel();

		VelocityContext ctx = new VelocityContext();
		for (String key : model.keySet()) {
			ctx.put(key, model.get(key));
		}

		StringWriter sw = new StringWriter();
		String logTag = "VELOCITY";
		boolean result = Velocity.evaluate(ctx, sw, logTag, input);

		return sw.toString();
	}

	public static String generateCode(Model model, String inputText) {
		VelocityContext ctx = new VelocityContext();

		populateVelocityContext(ctx, model);

		StringWriter sw = new StringWriter();
		String logTag = "VELOCITY";
		boolean result = Velocity.evaluate(ctx, sw, logTag, inputText);

		return sw.toString();
	}

	private static void populateVelocityContext(VelocityContext ctx, Model model) {
		if (model.getParent() != null) {
			populateVelocityContext(ctx, model.getParent());
		}

		ctx.put(model.getModelName(), model);

		// why did I comment this? this should be uncommented.
		// if (model.isObject()) {
		// for (String key : model.getObjectModel().keySet()) {
		// ctx.put(key, model.getObjectModel().get(key));
		// }
		// }

		// only for root elements
		if (model.isObject() && model.getParent() == null) {
			for (String key : model.getObjectModel().keySet()) {
				ctx.put(key, model.getObjectModel().get(key));
			}
		}
	}
}